// backfill-updatedAt.js
const mongoose = require('mongoose')
const AboutUs = require('./models/AboutUs')
const Carousel = require('./models/Carousel')
const Education = require('./models/Education')
const Employment = require('./models/Employment')
const Entrepreneur = require('./models/Entrepreneur')
const File = require('./models/File')
const Mentorship = require('./models/Mentorship')
const Project = require('./models/Project')
const TokenBlacklist = require('./models/TokenBlacklist')
const User = require('./models/User')

const models = [AboutUs, Carousel, Employment, Education, Entrepreneur, Mentorship, Project, File, TokenBlacklist, User]

;(async () => {
  await mongoose.connect('mongodb://app_admin:app_admin123@8.152.0.91:27011/production_db?authSource=admin&directConnection=true')

  for (const Model of models) {
    const name = Model.modelName
    console.log(`\n[${name}] 开始补录 updatedAt …`)

    // 找出所有缺少 updatedAt 的文档
    const docs = await Model.find({ updatedAt: { $exists: false } })

    if (!docs.length) {
      console.log(`[${name}] 无需补录`)
      continue
    }

    const bulkOps = docs.map(doc => {
      // 1) 优先用你老字段里的“最后修改时间”
      const fallbackTime = doc.createdAt || doc._id.getTimestamp()

      return {
        updateOne: {
          filter: { _id: doc._id },
          update: { $set: { updatedAt: fallbackTime } }
        }
      }
    })

    await Model.bulkWrite(bulkOps)
    console.log(`[${name}] 已补录 ${docs.length} 条`)
  }

  console.log('\n✅ 全部完成')
  process.exit(0)
})().catch(err => {
  console.error(err)
  process.exit(1)
})
